import 'dart:async';
import 'dart:io';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart' as path;
import '../serve/file_serve.dart';

/// 记忆管理类，负责处理AI的长期记忆存储和检索
class Memory {
  late String _dbPath;
  late FileServe _fileServe;
  Database? _database;
  final Map<String, List<Map<String, dynamic>>> _cache = {};
  late DateTime _dbCreateTime;
  bool _initialized = false;
  
  /// 私有构造函数
  Memory._();
  
  /// 单例实例
  static final Memory _instance = Memory._();
  
  /// 获取单例实例
  static Memory get instance => _instance;
  
  /// 初始化记忆系统
  Future<void> initialize() async {
    if (_initialized) return;
    
    try {
      print('Memory: 开始初始化记忆系统');
      
      _fileServe = FileServe();
      await _fileServe.initialize();
      
      _dbPath = _fileServe.getMemoryDatabasePath();
      print('Memory: 记忆数据库路径: $_dbPath');
      
      // 获取数据库创建时间
      final dbFile = File(_dbPath);
      if (await dbFile.exists()) {
        final stat = await dbFile.stat();
        _dbCreateTime = stat.changed;
      } else {
        _dbCreateTime = DateTime.now();
      }
      
      // 初始化数据库连接
      await _initDatabase();
      
      _initialized = true;
      print('Memory: 记忆系统初始化完成');
    } catch (e) {
      print('Memory: 初始化失败: $e');
      print('Memory: 堆栈: ${StackTrace.current}');
      rethrow;
    }
  }
  
  /// 初始化数据库
  Future<void> _initDatabase() async {
    try {
      _database = await openDatabase(
        _dbPath,
        version: 1,
        onCreate: (Database db, int version) async {
          await db.execute('''
            CREATE TABLE logs (
              id INTEGER PRIMARY KEY AUTOINCREMENT,
              time TEXT NOT NULL,
              content TEXT NOT NULL
            )
          ''');
        },
      );
      print('Memory: 数据库连接建立成功');
    } catch (e) {
      print('Memory: 数据库初始化失败: $e');
      rethrow;
    }
  }
  
  /// 确保数据库已初始化
  Future<void> _ensureInitialized() async {
    if (!_initialized) {
      await initialize();
    }
    
    if (_database == null || !_database!.isOpen) {
      await _initDatabase();
    }
  }
  
  /// 记忆重要信息到数据库
  Future<bool> remember(String content) async {
    try {
      if (content.trim().isEmpty) {
        print('Memory: 空内容不予记忆');
        return false;
      }
      
      await _ensureInitialized();
      
      final now = DateTime.now();
      final timeStr = now.toIso8601String();
      
      await _database!.insert(
        'logs',
        {
          'time': timeStr,
          'content': content.trim(),
        },
      );
      
      print('Memory: 记忆已保存: ${content.substring(0, content.length > 50 ? 50 : content.length)}...');
      
      // 清空相关缓存
      _clearRelatedCache();
      
      // 执行遗忘逻辑
      await _forgetOldMemories();
      
      return true;
    } catch (e) {
      print('Memory: 记忆失败: $e');
      return false;
    }
  }
  
  /// 遗忘过期的记忆（超过90天的记录自动删除）
  Future<void> _forgetOldMemories() async {
    try {
      await _ensureInitialized();
      
      final now = DateTime.now();
      final cutoffDate = now.subtract(const Duration(days: 90));
      final cutoffStr = cutoffDate.toIso8601String();
      
      final deletedCount = await _database!.delete(
        'logs',
        where: 'time < ?',
        whereArgs: [cutoffStr],
      );
      
      if (deletedCount > 0) {
        print('Memory: 清理了 $deletedCount 条过期记忆');
      }
    } catch (e) {
      print('Memory: 清理过期记忆失败: $e');
    }
  }
  
  /// 搜索记忆信息
  Future<List<Map<String, dynamic>>> search(String query) async {
    try {
      if (query.trim().isEmpty) {
        return [];
      }
      
      await _ensureInitialized();
      
      // 检查缓存
      if (_cache.containsKey(query)) {
        print('Memory: 从缓存返回搜索结果: $query');
        return _cache[query]!;
      }
      
      final results = await _database!.query(
        'logs',
        where: 'content LIKE ?',
        whereArgs: ['%$query%'],
        orderBy: 'time DESC',
        limit: 50, // 限制搜索结果数量
      );
      
      // 转换结果格式
      final formattedResults = results.map((row) => {
        'id': row['id'],
        'time': row['time'],
        'content': row['content'],
      }).toList();
      
      // 更新缓存
      _cache[query] = formattedResults;
      
      print('Memory: 搜索 "$query" 找到 ${formattedResults.length} 条记忆');
      return formattedResults;
    } catch (e) {
      print('Memory: 搜索记忆失败: $e');
      return [];
    }
  }
  
  /// 清空搜索缓存
  void clearCache() {
    _cache.clear();
    print('Memory: 搜索缓存已清空');
  }
  
  /// 清空与特定内容相关的缓存
  void _clearRelatedCache() {
    _cache.clear(); // 简单起见，清空所有缓存
  }
  
  /// 获取最近的记忆信息用于对话上下文
  Future<List<Map<String, String>>> getRecentMemories({int limit = 20}) async {
    try {
      await _ensureInitialized();
      
      final results = await _database!.query(
        'logs',
        orderBy: 'time DESC',
        limit: limit,
      );
      
      final messages = <Map<String, String>>[];
      
      for (final row in results.reversed) { // 按时间正序排列
        messages.add({
          'role': 'system',
          'content': '<memory>${row['content']}</memory>',
        });
      }
      
      if (messages.isNotEmpty) {
        messages.add({
          'role': 'system',
          'content': '以上被<memory></memory>标记的是你的记忆信息',
        });
      }
      
      print('Memory: 获取了 ${messages.length - (messages.isNotEmpty ? 1 : 0)} 条最近记忆');
      return messages;
    } catch (e) {
      print('Memory: 获取最近记忆失败: $e');
      return [];
    }
  }
  
  /// 获取所有记忆信息
  Future<List<Map<String, dynamic>>> getAllMemories() async {
    try {
      await _ensureInitialized();
      
      final results = await _database!.query(
        'logs',
        orderBy: 'time DESC',
      );
      
      print('Memory: 获取所有记忆，共 ${results.length} 条');
      return results;
    } catch (e) {
      print('Memory: 获取所有记忆失败: $e');
      return [];
    }
  }
  
  /// 获取数据库统计信息
  Future<Map<String, dynamic>> getStats() async {
    try {
      await _ensureInitialized();
      
      // 获取总记录数
      final countResult = await _database!.rawQuery('SELECT COUNT(*) as count FROM logs');
      final totalCount = countResult.first['count'] as int;
      
      // 获取时间范围
      final timeRangeResult = await _database!.rawQuery(
        'SELECT MIN(time) as earliest, MAX(time) as latest FROM logs WHERE time IS NOT NULL'
      );
      
      final timeRange = timeRangeResult.first;
      
      return {
        'totalRecords': totalCount,
        'earliestRecord': timeRange['earliest'] ?? '无记录',
        'latestRecord': timeRange['latest'] ?? '无记录',
        'databaseCreated': _dbCreateTime.toIso8601String(),
      };
    } catch (e) {
      print('Memory: 获取统计信息失败: $e');
      return {
        'totalRecords': 0,
        'earliestRecord': '无记录',
        'latestRecord': '无记录',
        'databaseCreated': DateTime.now().toIso8601String(),
      };
    }
  }
  
  /// 根据时间范围获取记忆
  Future<List<Map<String, dynamic>>> getMemoriesByTimeRange(
    DateTime startTime,
    DateTime endTime,
  ) async {
    try {
      await _ensureInitialized();
      
      final results = await _database!.query(
        'logs',
        where: 'time BETWEEN ? AND ?',
        whereArgs: [startTime.toIso8601String(), endTime.toIso8601String()],
        orderBy: 'time DESC',
      );
      
      print('Memory: 获取时间范围 ${startTime.toIso8601String()} 到 ${endTime.toIso8601String()} 的记忆，共 ${results.length} 条');
      return results;
    } catch (e) {
      print('Memory: 根据时间范围获取记忆失败: $e');
      return [];
    }
  }
  
  /// 删除指定ID的记忆
  Future<bool> deleteMemory(int id) async {
    try {
      await _ensureInitialized();
      
      final deletedCount = await _database!.delete(
        'logs',
        where: 'id = ?',
        whereArgs: [id],
      );
      
      if (deletedCount > 0) {
        print('Memory: 删除记忆成功，ID: $id');
        _clearRelatedCache();
        return true;
      } else {
        print('Memory: 未找到要删除的记忆，ID: $id');
        return false;
      }
    } catch (e) {
      print('Memory: 删除记忆失败: $e');
      return false;
    }
  }
  
  /// 更新记忆内容
  Future<bool> updateMemory(int id, String newContent) async {
    try {
      await _ensureInitialized();
      
      if (newContent.trim().isEmpty) {
        print('Memory: 更新内容为空');
        return false;
      }
      
      final updatedCount = await _database!.update(
        'logs',
        {'content': newContent.trim()},
        where: 'id = ?',
        whereArgs: [id],
      );
      
      if (updatedCount > 0) {
        print('Memory: 更新记忆成功，ID: $id');
        _clearRelatedCache();
        return true;
      } else {
        print('Memory: 未找到要更新的记忆，ID: $id');
        return false;
      }
    } catch (e) {
      print('Memory: 更新记忆失败: $e');
      return false;
    }
  }
  
  /// 关闭数据库连接
  Future<void> close() async {
    try {
      if (_database != null && _database!.isOpen) {
        await _database!.close();
        _database = null;
        print('Memory: 数据库连接已关闭');
      }
    } catch (e) {
      print('Memory: 关闭数据库连接失败: $e');
    }
  }
  
  /// 获取记忆数据库路径
  String get databasePath => _dbPath;
  
  /// 检查记忆系统是否已初始化
  bool get isInitialized => _initialized;
}

/// 记忆工具函数集合，用于AI工具系统
class MemoryTools {
  static final Memory _memory = Memory.instance;
  
  /// 搜索记忆信息
  static Future<String> searchFromMemory(String query) async {
    try {
      final results = await _memory.search(query);
      
      if (results.isEmpty) {
        return "未找到相关记忆。";
      }
      
      final formattedResults = results
          .map((row) => "[${row['time']}] ${row['content']}")
          .join('\n');
      
      return formattedResults;
    } catch (e) {
      return "搜索记忆时发生错误: $e";
    }
  }
  
  /// 记忆重要信息
  static Future<String> remember(String content) async {
    try {
      // 验证内容是否值得记忆
      if (!_isWorthRemembering(content)) {
        return "内容不符合记忆标准，未保存。";
      }
      
      final success = await _memory.remember(content);
      
      if (success) {
        return "记忆已更新！";
      } else {
        return "记忆保存失败。";
      }
    } catch (e) {
      return "记忆时发生错误: $e";
    }
  }
  
  /// 获取记忆统计信息
  static Future<String> getMemoryStats() async {
    try {
      final stats = await _memory.getStats();
      
      return "记忆统计: "
          "总记录数=${stats['totalRecords']}, "
          "最早记录=${stats['earliestRecord']}, "
          "最新记录=${stats['latestRecord']}, "
          "数据库创建时间=${stats['databaseCreated']}";
    } catch (e) {
      return "获取记忆统计时发生错误: $e";
    }
  }
  
  /// 清空记忆搜索缓存
  static String clearMemoryCache() {
    try {
      _memory.clearCache();
      return "记忆缓存已清空！";
    } catch (e) {
      return "清空缓存时发生错误: $e";
    }
  }
  
  /// 获取最近的记忆信息，用于添加到对话上下文中
  static Future<List<Map<String, String>>> getRecentMemories({int limit = 10}) async {
    try {
      return await _memory.getRecentMemories(limit: limit);
    } catch (e) {
      print("获取最近记忆时发生错误: $e");
      return [];
    }
  }
  
  /// 判断内容是否值得记忆
  static bool _isWorthRemembering(String content) {
    final trimmedContent = content.trim().toLowerCase();
    
    // 排除无效聊天
    final invalidPatterns = [
      '你好',
      'hello',
      '知道了',
      '好的',
      '是的',
      '不是',
      '谢谢',
      '再见',
      '没有',
      '有',
      '对',
      '错',
      '嗯',
      '哦',
      '啊',
    ];
    
    // 如果内容太短或者匹配无效模式，则不记忆
    if (trimmedContent.length < 5) {
      return false;
    }
    
    for (final pattern in invalidPatterns) {
      if (trimmedContent == pattern || trimmedContent.startsWith('用户说$pattern')) {
        return false;
      }
    }
    
    // 检查是否包含用户相关信息
    final userInfoPatterns = [
      '用户',
      '喜欢',
      '不喜欢',
      '偏好',
      '习惯',
      '兴趣',
      '工作',
      '学习',
      '专业',
      '身份',
      '目标',
      '需要',
      '要求',
    ];
    
    for (final pattern in userInfoPatterns) {
      if (trimmedContent.contains(pattern)) {
        return true;
      }
    }
    
    // 默认不记忆
    return false;
  }
}
